<template>
	<div>
		<cl-crud @load="onLoad">
			<template #slot-delete="{scope}">
				<delBtn @del="crud.delete(scope.row)"></delBtn>
			</template>
			<template #slot-filter>
				<div class="nav base-flex" style="margin-right:10px">
					<div>
						<date-picker
							@change="
								val => crud.refresh({ startTime: val[0], endTime: val[1], page: 1 })
							"
							@refresh="crud.refresh({ startTime: '', endTime: '', page: 1 })"
						></date-picker>
					</div>
					<div class="nav-li">
						<filterClass
							@change="
								val =>
									crud.refresh({
										cid: val
									})
							"
						></filterClass>
					</div>
					<div class="nav-li">
						<filterGstatus
							@change="
								val =>
									crud.refresh({
										status: val
									})
							"
						></filterGstatus>
					</div>
				</div>
			</template>
			<template #table-column-goodInfo="{scope}">
				<good-info :item="scope.row"></good-info>
			</template>
			<template #table-column-couponInfo="{scope}">
				<coupon-info :item="scope.row"></coupon-info>
			</template>
			<template #table-column-isDHh="{scope}">
				<div>
					<el-tag v-if="scope.row.isDHh == 1" type="success">是</el-tag>
					<el-tag type="info" v-else>否</el-tag>
				</div>
			</template>
			<template #table-column-isNine="{scope}">
				<div>
					<el-tag v-if="scope.row.isNine == 1" type="success">是</el-tag>
					<el-tag type="info" v-else>否</el-tag>
				</div>
			</template>
			<template #table-column-platform="{scope}">
				{{
				scope.row.source | dict_platform
				}}
			</template>
			<template #slot-add>
				<el-button type="danger" size="mini" @click="addGoods()">录入商品</el-button>
			</template>
			<template #table-column-startTime="{scope}">
				<div style="text-align:left">
					<div>
						免单金额：
						<span style="color:red">{{ scope.row.mdMoney }}</span>
					</div>
					<div>
						总数：
						<span style="color:red">{{ scope.row.total }}</span>
					</div>
					<div>
						已领数量：
						<span style="color:red">{{ scope.row.receiveNum }}</span>
					</div>
					<div>
						剩余数量：
						<span style="color:red">{{ scope.row.surplus }}</span>
					</div>
					<div>活动开始时间：{{ scope.row.startTime | dateFormatLine }}</div>
					<div>活动结束时间：{{ scope.row.endTime | dateFormatLine }}</div>
				</div>
			</template>
			<template #slot-setSort="{scope}">
				<span class="setsort" @click="setGoodsort(scope.row)">修改</span>
			</template>
			<template #table-column-status="{scope}">
				<div>
					<el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
					<el-tag type="info" v-if="scope.row.status == 2">已下架</el-tag>
				</div>
			</template>
		</cl-crud>

		<cl-form ref="cl-form"></cl-form>
	</div>
</template>

<script>
import DatePicker from '@/components/common/date-picker';
import goodInfo from './components/list/good-info';
import couponInfo from './components/list/coupon-info';
import searchCounpon from './components/list/searchCoupon';
import filterClass from './components/filterClass';
import filterGstatus from './components/filterGstatus';
import stores from '@/utils/store';
import moment from 'moment';
export default {
	data() {
		return {
			crud: null,
			enterGoodsInfo: {}
		};
	},
	components: {
		goodInfo,
		couponInfo,
		// eslint-disable-next-line
		searchCounpon,
		filterClass,
		filterGstatus,
		DatePicker
	},
	created() {
		this.$service.common.userAppList().then(res => {
			let list = res.map(el => {
				return {
					label: el.name,
					value: el.key
				};
			});
			this.formList = list;
			this.crud.setData('upsert.items[prop:appPlatforms].component.options', this.formList);
		});
	},

	methods: {
		submitForm(formData) {
			this.crud.setForm('data', formData);
			this.crud.submit();
		},
		setGoodsort(item) {
			const self = this;
			this.$refs['cl-form'].open({
				props: {
					'label-width': '80px',
					width: '570px',
					center: true,
					'custom-class': 'custom-class-dialog-mini'
				},
				items: [
					{
						prop: 'pic',
						label: '商品主图：',
						span: 24,
						value: item.pic,
						component: {
							name: 'cl-upload'
						}
					},
					{
						prop: 'title',
						label: '商品标题',
						span: 24,
						value: item.title,
						component: {
							name: 'el-input',
							attrs: {
								size: 'mini'
							}
						}
					},
					{
						prop: 'ysqLevel',
						label: '排序值',
						span: 24,
						value: item.ysqLevel ? item.ysqLevel : 100,
						component: {
							name: 'ysqlevel-input',
							data() {
								return {
									value2: 0
								};
							},
							props: {
								value: [String, Number]
							},
							mounted() {
								this.value2 = this.value;
							},
							methods: {
								input(e) {
									this.$emit('input', e);
								}
							},
							render() {
								return (
									<div style="display:flex">
										<el-input-number
											controls-position="right"
											min={1}
											max={100000}
											onInput={this.input}
											v-model={this.value2}></el-input-number>
										<span style="color:red;margin-left:10px">
											* 序号越大，排序越靠前
										</span>
									</div>
								);
							}
						},
						rules: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
					},

					{
						prop: 'total',
						label: '免单总数',
						span: 24,
						value: item.total,
						component: {
							name: 'total-input',
							data() {
								return {
									value2: 0
								};
							},
							props: {
								value: [String, Number]
							},
							mounted() {
								this.value2 = this.value;
							},
							methods: {
								input(e) {
									this.$emit('input', e);
								}
							},
							render() {
								return (
									<div style="display:flex">
										<el-input-number
											controls-position="right"
											min={item.receiveNum}
											max={100000}
											onInput={this.input}
											v-model={this.value2}></el-input-number>
										<span style="color:red;margin-left:10px">
											* 剩余数量{' '}
											{this.value2 - item.receiveNum > 0
												? this.value2 - item.receiveNum
												: 0}
										</span>
									</div>
								);
							}
						},
						rules: [{ required: true, message: '免单总数不能为空', trigger: 'blur' }]
					},
					{
						prop: 'mdMoney',
						label: '免单金额',
						value: item.mdMoney,
						span: 15,
						component: {
							name: 'el-input-number',
							min: 0,
							max: 100000
						},
						rules: [{ required: true, message: '免单金额不能为空', trigger: 'blur' }]
					},
					{
						prop: 'status',
						label: '是否上架',
						span: 12,
						value: item.status,
						component: {
							name: 'el-input-number1',
							attrs: {
								'controls-position': 'right',
								min: 1,
								max: 10000
							},
							data() {
								return {
									value2: 1
								};
							},
							props: {
								value: [String, Number]
							},
							watch: {
								value(val) {
									this.value2 = val;
								}
							},
							methods: {
								change(e) {
									this.$emit('input', e);
								}
							},
							mounted() {
								this.value2 = this.value;
							},
							render() {
								return (
									<el-radio-group onChange={this.change} v-model={this.value2}>
										<el-radio label={1}>上架</el-radio>
										<el-radio label={2}>下架</el-radio>
									</el-radio-group>
								);
							}
						},
						rules: [{ required: true, message: '免单总数不能为空', trigger: 'blur' }]
					}
				],
				on: {
					submit({ data, close }) {
						self.$service.goodsMenagement.mdGoods
							.updateInfo({
								...data,
								gid: item.gid,
								id: item.id,
								mdId: item.mdId,
								receiveNum: data.total - item.receiveNum,
								zfbLevel: data.zfbLevel || 0
							})
							.then(() => {
								self.$message({
									message: '设置成功',
									type: 'success'
								});
								self.crud.refresh();
								close();
								return;
							})
							.catch(err => {
								self.$message.error(err);
							});
					}
				}
			});
		},
		onLoad({ ctx, app }) {
			const self = this;
			this.crud = app;

			ctx.service(this.$service.goodsMenagement.mdGoods)
				.set('dict', {
					label: {
						add: '添加用户'
					},
					api: {
						delete: 'deleteZeroGoods'
					}
				})
				.set('table', {
					columns: [
						{
							label: '序号',
							type: 'index',
							align: 'center',
							width: 80
						},
						{
							label: '商品信息',
							prop: 'goodInfo',
							align: 'left',
							'min-width': 400
						},
						{
							label: '优惠券信息',
							prop: 'couponInfo',
							align: 'left',
							'min-width': 350
						},
						{
							label: '月销量',
							prop: 'sale',
							align: 'center'
						},
						{
							label: '商品排序',
							prop: 'ysqLevel',
							align: 'center',
							sortable: 'custom',
							emptyText: '0',
							'min-width': 100
						},
						{
							label: '活动时间',
							prop: 'startTime',
							align: 'center',
							sortable: 'custom',
							'min-width': '250px'
						},
						{
							label: '佣金比例',
							prop: 'commissionRate',
							align: 'center'
						},
						{
							label: '9.9包邮',
							prop: 'isNine',
							align: 'center'
						},
						{
							label: '抖好货',
							prop: 'isDHh',
							align: 'center'
						},
						{
							label: '是否下架',
							prop: 'status',
							align: 'center',
							'min-width': 100
						},
						{
							label: '平台',
							prop: 'platform',
							align: 'center'
						}
					],

					op: {
						visible: true,
						layout: ['slot-setSort']
					}
				})
				.set('upsert', {
					props: {
						labelWidth: '120px',
						center: true,
						'custom-class': 'custom-class-dialog'
					},
					items: [
						{
							prop: 'pic',
							label: '商品主图：',
							span: 24,
							component: {
								name: 'cl-upload'
							}
						},
						{
							prop: 'title',
							label: '商品标题',
							span: 24,
							component: {
								name: 'el-input',
								attrs: {
									size: 'mini'
								}
							}
						},
						{
							prop: 'appPlatforms',
							label: '平台',
							span: 13,
							component: {
								name: 'el-select',
								options: [],
								attrs: {
									placeholder: '请选择平台',
									multiple: true
								},
								on: {
									change: id => {
										console.log(id);
									}
								}
							},
							rules: {
								required: true,
								message: '账号不能为空'
								// trigger: 'blur'
							}
						},
						{
							prop: 'url',
							props: {
								labelWidth: '0px'
							},
							component: {
								name: 'search-counpon',
								methods: {
									input(e) {
										this.$emit('input', e);
									},
									Goodsinfo(e) {
										self.enterGoodsInfo = e;
										// app.setForm('tljName', e.title.substring(0,10)); // 这个表单没名称……
									},
									perface(v) {
										app.setForm('tljMoney', v < 1 ? 1 : v);
									}
								},
								render() {
									return (
										<searchCounpon
											onInput={this.input}
											onGoodsInfo={this.Goodsinfo}
											onperface={this.perface}
											item={self.enterGoodsInfo}></searchCounpon>
									);
								}
							},
							rules: [{ required: true, message: '请先检索商品', trigger: 'blur' }]
						},
						{
							prop: 'mdMoney',
							label: '补贴金额：',
							component: {
								name: 'mdMoney_c',
								data() {
									return {
										value2: 0
									};
								},
								methods: {
									Change(e) {
										this.$emit('input', e);
										// if (
										// 	this.value2 >=
										// 	(self.enterGoodsInfo.endPrice -
										// 		self.enterGoodsInfo.hzQuanOver) *
										// 		0.8
										// ) {
										// 	self.$message.error(
										// 		'淘礼金金额不能大于商品券后价的80%'
										// 	);
										// }
									}
								},

								render() {
									return (
										<div style="display:flex">
											<el-input-number
												max={
													Number(
														self.enterGoodsInfo.endPrice -
															self.enterGoodsInfo.hzQuanOver
													) || 0
												}
												step={0.01}
												min={0}
												v-model={this.value2}
												onChange={this.Change}></el-input-number>
											<div style="margin-left:10px">
												到手价格￥
												<span style="color:red">
													{(
														parseFloat(
															self.enterGoodsInfo.endPrice || 0
														) -
														(this.value2 ? this.value2 : 0) -
														(self.enterGoodsInfo.hzQuanOver || 0)
													).toFixed(2)}
												</span>
												元
											</div>
										</div>
									);
								}
							}
						},
						{
							prop: 'total',
							label: '活动商品个数：',
							span: 11,
							value: parseInt(Math.random() * (10000 - 5000 + 1) + 5000, 10),
							component: {
								name: 'el-input-number',
								attrs: {
									'controls-position': 'right',
									min: 1,
									max: 10000
								}
							},
							rules: [
								{
									required: true,
									message: '请输入活动商品数量',
									trigger: 'blur'
								}
							]
						},
						// {
						// 	prop: 'time',
						// 	label: '活动时间：',
						// 	span: 16,
						// 	component: {
						// 		name: 'el-date-picker',
						// 		attrs: {
						// 			type: 'datetimerange',
						// 			'value-format': 'yyyy-MM-dd HH:mm:ss'
						// 		}
						// 	},
						// 	rules: [
						// 		{
						// 			required: true,
						// 			message: '请选择活动时间',
						// 			trigger: 'blur'
						// 		}
						// 	]
						// },
						{
							prop: 'time',
							label: '活动开始时间',
							span: 14,
							component: {
								name: 'el-date-picker',
								props: {
									type: 'datetime',
									'value-format': 'yyyy-MM-dd HH:mm:ss'
								}
							},
							rules: [
								{
									required: true,
									message: '开始时间不能为空',
									trigger: 'blur'
								},
								{
									validator: (rules, value, callback) => {
										const h = app.getData('upsert.form.hour') || 0;

										if (
											moment(value)
												.add(h, 'hour')
												.isBefore(moment())
										) {
											callback(new Error('开始时间不能小于当前时间'));
										} else {
											callback();
										}
									}
								}
							]
						},
						{
							prop: 'hour',
							label: '持续时间（h）',
							span: 10,
							value: 24,
							component: {
								name: 'el-input-number',
								props: {
									min: 0
								}
							},
							rules: {
								required: true,
								message: '持续时间不能为空',
								trigger: 'blur'
							}
						},
						{
							prop: 'ysqLevel',
							label: '商品排序：',
							value: 100,
							component: {
								name: 'ysqlevels',
								data() {
									return {
										ysqLevel: 100
									};
								},
								props: {
									value: [String, Number]
								},
								mounted() {
									this.ysqLevel = this.value;
								},
								methods: {
									input(e) {
										this.$emit('input', e);
									}
								},
								render() {
									return (
										<div>
											<el-input-number
												v-model={this.ysqLevel}
												controls-position="right"
												onInput={this.input}
												min={1}
												max={10000}></el-input-number>
											<span style="color:#999999;margin-left:10px">
												序号越大，排序越靠前
											</span>
										</div>
									);
								}
							}
						},
						{
							prop: 'status',
							label: '商品状态：',
							value: 1,
							component: {
								name: 'g_radio',
								data() {
									return {
										value2: 1
									};
								},
								props: {
									value: [String, Number]
								},
								mounted() {
									this.value2 = Number(this.value || 1);
								},
								methods: {
									change(e) {
										this.$emit('input', e);
									}
								},
								render() {
									return (
										<el-radio-group
											onChange={this.change}
											v-model={this.value2}>
											<el-radio label={1}>上架</el-radio>
											<el-radio label={2}>下架</el-radio>
										</el-radio-group>
									);
								}
							}
						}
					],
					op: {
						visible: true,
						layout: ['confirm']
					}
				})
				.set('layout', [
					['refresh-btn', 'slot-add', 'query', 'flex1', 'slot-filter', 'search-key'],
					['data-table'],
					['flex1', 'pagination']
				])
				.on('refresh', async (params, { next, render }) => {
					// if(!params.startTime){
					// 	params.startTime = moment().format('YYYY-MM-DD 00:00:00');
					// 	params.endTime = moment().format('YYYY-MM-DD 23:59:59');
					// }
					let { list } = await next(params);
					list.map(item => {
						item.commissionRate = item.commissionRate + '%';
						item.sale = item.sale + '件';
					});
					render(list);
				})
				.on('open', () => {
					// 打开时清空商品数据
					this.enterGoodsInfo = {};
					this.getPlatform();
					app.setForm(
						'time',
						moment().format('YYYY-MM-DD HH:mm:ss')
						// [
						// 	// moment(new Date().getTime() + 86400000).format('YYYY-MM-DD 00:00:00')
						// 	// moment(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss'),
						// 	// moment(new Date().getTime() + 172800000).format('YYYY-MM-DD 00:00:00')
						// ]
					);
				})
				.on('submit', (isOpen, data, { next }) => {
					stores.set('appPlatforms', data.appPlatforms); // 缓存用户选择的平台
					data.appPlatforms = data.appPlatforms.join(',');
					data.quanMLink = this.enterGoodsInfo.quanMLink; // 定金
					data.hzQuanOver = this.enterGoodsInfo.hzQuanOver; // 立减
					next({
						...data,
						...data.url,
						// startTime: data.time[0],
						// endTime: data.time[1],
						startTime: data.time,
						endTime: moment(data.startTime)
							.add(data.hour, 'hour')
							.format('YYYY-MM-DD HH:mm:ss'),
						isFree: 1,
						type: 7
					});
				})
				.done();

			app.refresh({
				status: 1,
				isFree: 1,
				type: 7,
				prop: 'createTime',
				order: 'desc'
			});
		},
		addGoods() {
			this.crud.add();
		},
		// 获取平台缓存
		getPlatform() {
			let data = stores.get('appPlatforms');
			if (data) {
				this.crud.setForm('appPlatforms', data);
			} else {
				this.crud.setForm('appPlatforms', [this.formList[0].value]);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.setsort {
	color: $color-link;
	cursor: pointer;
	margin: 5px 5px 5px 15px;
	:hover {
		opacity: 0.8;
	}
}
.nav {
	font-size: $font12;
	.nav-li {
		margin-left: 10px;
	}
}
</style>
